import React from 'react';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  BarElement,
  Title,
  Tooltip,
  Legend,
} from 'chart.js';
import { Bar, Line } from 'react-chartjs-2';
import { Product, RateRecord } from '../../types/product';
import { analyzeProfitVolatility } from '../../utils/calculations';

ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  BarElement,
  Title,
  Tooltip,
  Legend
);

interface ProductComparisonProps {
  products: Product[];
}

const ProductComparison: React.FC<ProductComparisonProps> = ({ products }) => {
  // 比较期限
  const periods = [30, 90, 180, 365];

  // 图表数据
  const rateChartData = {
    labels: products.map(p => p.name),
    datasets: [
      {
        label: '银行宣传年化率',
        data: products.map(p =>
          p.historyRates[0]?.advertisedRate || 0
        ),
        backgroundColor: 'rgba(255, 99, 132, 0.5)',
      },
      {
        label: '实际年化率',
        data: products.map(p =>
          p.historyRates[0]?.rate || 0
        ),
        backgroundColor: 'rgba(53, 162, 235, 0.5)',
      },
    ],
  };

  // 波动率数据
  const volatilityData = {
    labels: products.map(p => p.name),
    datasets: [
      {
        label: '收益波动率',
        data: products.map(p => {
          const dailyProfits = p.historyRates.map((rate: RateRecord) =>
            rate.dailyProfit || (rate.advertisedRate / 365 * 10000)
          );
          const { deviation } = analyzeProfitVolatility(dailyProfits);
          return deviation * 100;
        }),
        backgroundColor: 'rgba(75, 192, 192, 0.5)',
      },
    ],
  };

  // 不同期限预期收益对比
  const expectedProfitData = {
    labels: products.map(p => p.name),
    datasets: periods.map(period => ({
      label: `${period}天预期收益`,
      data: products.map(p => {
        const rate = p.historyRates[0]?.advertisedRate || 0;
        return (rate / 365 * period).toFixed(2);
      }),
      backgroundColor: 'rgba(255, 206, 86, 0.5)',
    })),
  };

  const options = {
    responsive: true,
    plugins: {
      legend: {
        position: 'top' as const,
      },
    },
    scales: {
      y: {
        beginAtZero: true,
      },
    },
  };

  return (
    <div>
      <div style={{ marginBottom: '2rem' }}>
        <h3>年化收益率对比</h3>
        <Bar data={rateChartData} options={options} />
      </div>

      <div style={{ marginBottom: '2rem' }}>
        <h3>收益波动率对比</h3>
        <Bar data={volatilityData} options={options} />
      </div>

      <div>
        <h3>不同期限预期收益对比</h3>
        <Bar data={expectedProfitData} options={options} />
      </div>
    </div>
  );
};

export default ProductComparison;